import { Theme, ThemeBook } from '../models';
import redis from '../utils/redis';

export default function (router) {
  /**
   * 前端接口
   * 首页获取栏目数据的接口
   */
  router.get('/api/front/theme', async ctx => {
    // 如果存在缓存直接返回
    const cacheData = await redis.get('theme-data');
    if (cacheData) {
      await ctx.json(true, '获取轮播图成功', { ...JSON.parse(cacheData), cached: true });
      return;
    }
    return new Promise(async resolveOut => {
      // 查找出所有的需要显示的栏目
      const allThemes = await Theme.find({ show: true }, 'name layout flush').sort({ priority: 1 });
      const promiseArr = [];
      for (let i = 0; i < allThemes.length; i++) {
        let num = 3;
        switch (allThemes[i].layout) {
          case 1:
            num = 4;
            break;
          case 2:
            num = 5;
            break;
          case 3:
            num = 6;
            break;
          default:
            break;
        }
        promiseArr.push(
          new Promise(async resolve => {
            const books = await ThemeBook.find({ theme: allThemes[i]._id }).sort({ priority: 1, create_time: 1 }).limit(num).populate({
              path: 'book',
              select: 'name author img_url des classify create_time'
            });
            resolve({
              _id: allThemes[i].id,
              name: allThemes[i].name,
              flush: allThemes[i].flush,
              layout: allThemes[i].layout,
              books: books.map(item => item.book)
            });
          })
        );
      }
      Promise.all(promiseArr).then(async result => {
        redis.set('theme-data', JSON.stringify({ list: result }), 'EX', 60 * 10);
        await ctx.json(true, '获取主题成功', { list: result });
        resolveOut(true);
      });
    });
  });

  /**
   * 前端接口
   * 首页点击换一批对应的接口
   */
  router.get('/api/front/theme/flush', async ctx => {
    let { page, themeId } = ctx.request.query;
    if (page) {
      page = parseInt(page);
      if (page < 2) {
        page = 2;
      }
    } else {
      page = 2;
    }
    if (!themeId) await ctx.json(false, '参数错误');
    const thisTheme = await Theme.findById(themeId, 'layout');
    if (!thisTheme) await ctx.json(false, '参数错误');
    let num = 3;
    switch (thisTheme.layout) {
      case 1:
        num = 4;
        break;
      case 2:
        num = 5;
        break;
      case 3:
        num = 6;
        break;
      default:
        break;
    }
    const total = await ThemeBook.countDocuments({ theme: themeId });
    const result = await ThemeBook.find({ theme: themeId })
      .sort({ priority: 1, create_time: 1 })
      .skip((page - 1) * num)
      .limit(num)
      .populate({
        path: 'book',
        select: 'name author img_url des classify create_time'
      });
    await ctx.json(true, '刷新成功', { list: result.map(item => item.book), noMore: page * num >= total });
  });

  /**
   * 后台接口
   * 列出所有的主题
   */
  router.get('/api/admin/theme', async ctx => {
    const { page, limit } = ctx.parsePageAndLimit(ctx.request.query);
    const { search } = ctx.request.query;
    const queryParam = {};
    if (search) {
      const reg = new RegExp(search.toString('utf8').trim(), 'i');
      queryParam.name = reg;
    }
    const list = await Theme.find(queryParam)
      .skip((page - 1) * limit)
      .limit(limit)
      .sort({ priority: 1, show: -1, create_time: 1 });
    const total = await Theme.countDocuments();
    await ctx.json(true, '获取主题列表成功', { list, total });
  });

  /**
   * 后台接口
   * 新增主题
   */
  router.post('/api/admin/theme', async ctx => {
    const { name, des, show, layout, flush } = ctx.request.body;
    const maxPriority = await Theme.countDocuments();
    const result = await Theme.create({
      priority: maxPriority + 1,
      name: name,
      des: des,
      book_num: 0,
      show: show,
      layout: layout,
      flush: flush,
      create_time: new Date()
    });
    await ctx.json(true, '新增主题成功', { result, total: maxPriority + 1 });
  });

  /**
   * 后台接口
   * 获取主题详细信息
   */
  router.get('/api/admin/theme/:id', async ctx => {
    const { id } = ctx.params;
    const thisTheme = await Theme.findById(id).populate({
      path: 'books.bookid',
      select: { chapters: 0 }
    });
    await ctx.json(true, '获取主题详情成功', thisTheme);
  });

  /**
   * 后台接口
   * 修改主题
   */
  router.put('/api/admin/theme/:id', async ctx => {
    const { id } = ctx.params;
    const result = await Theme.updateOne(
      { _id: id },
      {
        $set: ctx.request.body
      }
    );
    if (result.ok === 1) {
      const newest = await Theme.findById(id);
      await ctx.json(true, '更新主题成功', newest);
    } else {
      await ctx.json(true, '更新主题失败', result);
    }
  });

  /**
   * 后台接口
   * 删除主题
   */
  router.delete('/api/admin/theme/:id', async ctx => {
    const { id } = ctx.params;
    const thisData = await Theme.findOne({ _id: id }, 'priority');
    const operation = await Theme.deleteOne({ _id: id });
    // 更新顺序
    const update = await Theme.updateMany({ priority: { $gt: thisData.priority } }, { $inc: { priority: -1 } });
    if (operation.ok && update.ok) {
      await ctx.json(true, '删除主题成功');
    } else {
      await ctx.json(false, '删除主题失败');
    }
  });

  /**
   * 后端接口
   * 交换主题位置
   */
  router.post('/api/admin/theme/exchange', async ctx => {
    const { from: fromIndex, to: toIndex, id } = ctx.request.body;
    if (!fromIndex || !toIndex) await ctx.json(false, '参数错误');
    if (fromIndex === toIndex) await ctx.json(false, '交换顺序不能相同');

    let updateCur, updateOther;
    if (fromIndex > toIndex) {
      updateOther = await Theme.updateMany({ priority: { $lt: fromIndex, $gte: toIndex } }, { $inc: { priority: 1 } });
      updateCur = await Theme.updateOne({ _id: id }, { $set: { priority: toIndex } });
    } else {
      updateOther = await Theme.updateMany({ priority: { $gt: fromIndex, $lte: toIndex } }, { $inc: { priority: -1 } });
      updateCur = await Theme.updateOne({ _id: id }, { $set: { priority: toIndex } });
    }

    if (updateCur.ok && updateOther.ok) {
      await ctx.json(true, '交换成功');
    } else {
      await ctx.json(false, '交换失败');
    }
  });
}
